package com.gzgs.controller;
import com.gzgs.dao.SysUserDao;
import com.gzgs.dao.SysUserRoleDao;
import com.gzgs.pojo.SysFile;
import com.gzgs.pojo.SysUser;
import com.gzgs.pojo.SysUserRole;
import com.gzgs.service.FilePathService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.management.relation.Role;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@Controller
public class LoginController {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private FilePathService filePathService;

    @RequestMapping("/")
    public String toLogin(){
        return "login.html";
    }

    @RequestMapping("/login")
    public String login(Model model,
                        @Param("username")String username,
                        @Param("password")String password,
                        HttpSession session){

        SysUser users = sysUserDao.selectByNameAndPw(username,password);
        if (users==null){
            model.addAttribute("msg","用户名不存在或密码错误！");
            return "login.html";
        }else {
                session.setAttribute("userlogin",username);
                model.addAttribute("user",users);
                List<SysFile> files = filePathService.getAll();
                model.addAttribute("fileList",files);
                List<SysUserRole> roles = sysUserRoleDao.selectByUid(users.getId());
                int rolecount = roles.size();
                session.setAttribute("userrole",rolecount);
                return "home.html";
        }
    }

    @RequestMapping("/save")
    public String saveStu(Model model, @Param("username")String username,@Param("password")String password) throws IOException {
        SysUser user = sysUserDao.selectByName(username);
        if (user == null){
            SysUser sysUser = new SysUser();
            sysUser.setName(username);
            sysUser.setPassword(password);
            sysUserDao.insert(sysUser);
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(sysUserDao.selectByName(username).getId());
            userRole.setRoleId(2);
            sysUserRoleDao.insert(userRole);
            model.addAttribute("samsg","注册成功");
            return "login.html";
        }else {
            model.addAttribute("samsg","用户名已存在");
            return "login.html";
        }
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "/login.html";
    }

}
